﻿namespace Away.Admin.Repositories.Implements;

[ServiceInject(ServiceLifetime.Scoped)]
internal class ApiResourceRepository : SystemRepository, IApiResourceRepository
{
    public ApiResourceRepository(SystemsDbContext context) : base(context)
    {
    }

    public bool AddApiResource(SysApiResource model)
    {
        Add(model);
        return Save();
    }

    public ApiResult GetApiResourcePage(ApiResourceSearch search)
    {
        var cond = CondBuilder.New<SysApiResource>(true)
            .And(search.Id > 0, o => o.Id == search.Id)
            .And(!string.IsNullOrWhiteSpace(search.Group), o => o.Group.Contains(search.Group!))
            .And(!string.IsNullOrWhiteSpace(search.Url), o => o.Url.Contains(search.Url!))
            .And(!string.IsNullOrWhiteSpace(search.ApiName), o => o.ApiName.Contains(search.ApiName!));

        var querydb = Query<SysApiResource>().Where(cond);
        var total = querydb.Count();
        var items = querydb.OrderByDescending(o => o.Id).Page(search).ToList();
        return ApiResult.Page(total, items);
    }

    public bool RemoveApiResource([Required] int[] ids)
    {
        var items = Query<SysApiResource>().Where(o => ids.Contains(o.Id)).ToArray();
        if (!items.Any())
        {
            return true;
        }
        Remove(items);
        return Save();
    }

    public bool UpdateApiResource(SysApiResource model)
    {
        Update(model);
        return Save();
    }

    public void ImportApiResource(List<SysApiResource> entitys)
    {
        foreach (var entity in entitys)
        {
            var exist = Query<SysApiResource>().Any(o => o.Url == entity.Url && o.Method == entity.Method);
            if (!exist)
            {
                Add(entity);
                Save();
            }
        }
    }

    public List<SysApiResource> GetApiResourceList()
    {
        return Query<SysApiResource>().ToList();
    }
}
